package cn.edu.gzist.chapter09spring.service;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 *  https://cron.qqe2.com/
 */


@Service
@EnableScheduling
public class ScheduleTaskService {

    @Scheduled(cron ="0/1 * * * * ? " )
    public void task1(){
        System.out.println("++++++++++++++++++++++++++");
        System.out.println("task1: " + new Date());
        System.out.println("current thread: " + Thread.currentThread().getName());
        System.out.println("++++++++++++++++++++++++++");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    @Scheduled(cron ="0/1 * * * * ? " )
    public void task2(){
        System.out.println("++++++++++++++++++++++++++");
        System.out.println("task2: " + new Date());
        System.out.println("current thread: " + Thread.currentThread().getName());
        System.out.println("++++++++++++++++++++++++++");
    }
    // 固定速率：每 3 秒执行一次，不管任务执行要多久
    @Scheduled(fixedRate = 3000)
    public void taskWithFixdRate(){
        System.out.println("固定速率任务开始");
        // 任务逻辑
    }

    // 固定速率：每 3 秒执行一次，不管任务执行要多久
    @Scheduled(fixedRateString = "3000")
    public void taskWithFixdRateString(){
        System.out.println("固定速率任务开始");
        // 任务逻辑
    }

    // 固定延迟：上次执行完成后等待 3 秒在执行
    @Scheduled(fixedDelay = 3000)
    public void taskWithFixedDelay(){
        System.out.println("固定延迟任务开始");
        // 任务逻辑
    }
    // 固定延迟：上次执行完成后等待 3 秒在执行
    @Scheduled(fixedDelayString = "3000")
    public void taskWithFixedDelayString(){
        System.out.println("固定延迟任务开始");
        // 任务逻辑
    }

    // 组合使用：首次延迟 1 秒，之后每秒 5 秒执行一次
    @Scheduled(initialDelay = 1000, fixedRate = 5000)
    public void taskWithInitialDelay(){
        System.out.println("首次延迟任务开始");
        // 任务逻辑
    }

    // cron表达式，每分钟的第 0 秒执行一次
    @Scheduled(cron = "0 * * * * *")
    public void taskWithCron(){
        System.out.println("cron任务开始");
        // 任务逻辑
    }
}
